var $ = require('jquery');
var util = require('imutil');
var Backbone = require('backbone');
var tpl = require('../tpl');

var Users = require('../model/users');
var dialog = require('dialog');
var bus = require('bus');
var Hammer = require('hammer');

module.exports = Backbone.View.extend({
	el: null,
	collection: null,
	template: tpl.contacts.list,
	events: {
		'click .J-im-item': 'chat2',
        "click .J-im-contact-del" : "clear",
        "click .J-im-backhome":"backHome"
	},
	initialize: function(options, api){
		this.api = api;
		this.render();
		
		this.listenTo(this.collection, 'reset', function(){
			this.render();
		});
		
		// 收消息时，列表不做动画
		this.listenTo(bus, 'receiveMessage messageSync', function(msg, strange){
            this.collection.reset(this.api.models.contacts.toJSON(), {silent: true});
			this.render(true);
        });
		
        this.listenTo(bus,'deleteRecentContactNty',function(uid){
            this.deleteUser(uid);
        });
		
		// 调整列表可显示区域高度，解决移动设备下拉到底时拖动整个界面问题
		this.listenTo(bus, 'window.resize', function(size){
			this.adjustSize(size);
		});

	},
	/**
	* 调整列表可显示区域高度，解决移动设备下拉到底时拖动整个界面问题
	*/
	adjustSize: function(size){
		var _this = this;
		
		this.api.ready(function(){
			size = size || util.winSize();
			
			// 样式规定值
			// 可视区域高度 - 4.4rem
			var height = size.height - 4.4 * parseFloat($('html').css('fontSize'));
			_this.$('.J-im-contact-box').css({height: height});
		});
	},
	render: function(noAnimate){
		var _this = this;
		
		this.api.ready(function(){
            var users = _this.collection.toJSON();
            users.sort(function(a,b){
                return b.lastChatTimestamp-a.lastChatTimestamp
            });
			_this.$el.html(_this.template(_this.api.servant.fuse({
				contacts:users,
				isSearchResult: _this.isSearchResult,
				doAnimate: !noAnimate
			}, _this.api.i18n.contacts)));
			
			// 调整列表可显示区域高度，解决移动设备下拉到底时拖动整个界面问题
			_this.adjustSize();
			// 动画化显示
			!noAnimate && _this.animate();
			// 滑动删除
			_this.showDelete();
		});
	},
	animate: function(){
		var api = this.api;
		var $items = $('.J-im-item', this.$el);
		
		if(!$items.length){
			return;
		}
		
		if(api.loading && !api.isReady){
			api.loading.on('hide', function(){
				var delay = 0;
				
				$items.each(function(i, item){
					setTimeout(function(){
						$(item).addClass("im-anim-contact");
					}, delay + i * 100);
				});
			});
		}else{
			var delay = 0;
				
			$items.each(function(i, item){
				setTimeout(function(){
					$(item).addClass("im-anim-contact");
				}, delay + i * 60);
			});
		}
	},
	chat2: function(e){
		e.preventDefault();
		e.stopPropagation();
        var nameLeft = $(e.currentTarget).find(".J-im-contact-info").css("left");
		if(nameLeft=="auto" || nameLeft =="" || /^0(?:px|em|rem)?$/.test(nameLeft)){
            this.api.forward('chat2/' + $(e.currentTarget).attr('cz-uid'));
        }else{
            $(e.currentTarget).find(".J-im-contact-info").css("left","auto");
        }

	},
    clear: function(e) {
        e.preventDefault();
        e.stopPropagation();
        var that = this;
        that.api.mask.show();
        dialog.confirm('Attention', 'Delete This Conference?', function(){
            var delUid =$(e.currentTarget).parents(".J-im-item").attr("cz-uid");
            that.deleteUser(delUid);
            that.api.mask.hide();
        },function(){
            that.api.mask.hide();
        });

    },
    deleteUser:function(uid){
        var that = this;
        var delData =  that.collection.get(uid);
        that.api.sdk.deleteContacts(uid,function(){
            that.collection.remove(delData);
            that.collection.reset(that.collection.toJSON());
        })
    },
    backHome:function(e){
        e.preventDefault();
        this.api.backward();
    },
    showDelete:function(e){
        var that = this;
		// 搜索结果不可以删除
        !this.isSearchResult && this.$(".J-im-contact-info").each(function(index, item) {
			var hammer = new Hammer(item);

            hammer.on("panstart",function(e){
                that.$(".J-im-contact-info").css("left","");
            });

			hammer.on("panmove",function(e){
			   $(item).css("left", e.deltaX<=0?e.deltaX:0);
			});
			
			hammer.on("panend",function(e){
				if(parseInt($(item).css("left"))< -50){
					$(item).css("left", "-3.75rem");
				}else{
					$(item).css("left","");
				}
				return false;
			});

        });
    }
});